﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using BootstrapBlazor.Components;
using Messhall.Application.Dto.Permissions.Requests;
using Messhall.Application.Dto.Permissions.Responses;
using Messhall.Application.Dto.Users.Requests;
using Messhall.Application.Dto.Users.Responses;
using Messhall.Framework.Converts;
using Messhall.HostService.Interface.Permission;
using Messhall.HostService.Proxy;
using Messhall.UI.Permission.Model;
using Messhall.UI.Permission.Model.Permissions;
using Messhall.UI.Permission.Pages.Users;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.Extensions.Localization;

namespace Messhall.UI.Permission.Pages.Permission;

public partial class List
{
    private readonly IPermission _permissionService = ServiceFactory.Create<IPermission>();

    [NotNull] private Modal _smailModal;

    [NotNull] private IEnumerable<MenuItem>? IconSideMenuItems { get; set; }
    // = new List<MenuItem>
    // {
    //     new MenuItem() {Text = "跳转组件库", Icon = "fa fa-fw fa-home", Url = "https://www.blazor.zone/components"},
    //     new MenuItem()
    //     {
    //         IsCollapsed = false,
    //         Text = "系统权限", Icon = "fa fa-fw fa-table", Url = "table", IsActive = true,
    //         Items = new List<MenuItem>()
    //         {
    //             new MenuItem()
    //             {
    //                 IsCollapsed = false, Text = "角色", Icon = "fa fa-fw fa-database", Url = "/Role/List"
    //             },
    //             new MenuItem()
    //             {
    //                 IsCollapsed = false, Text = "用户", Icon = "fa fa-fw fa-database", Url = "/Users/List"
    //             },
    //             new MenuItem()
    //             {
    //                 IsCollapsed = false, Text = "菜单设置", Icon = "fa fa-fw fa-database", Url = "/Pemission/List"
    //             },
    //         }
    //     },
    // };

    private PermissionModel _permissionModel = new();
    private AuthorityModel _authorityModel = new();
    private MenuItem _selectMenuItem;


    /// <summary>
    /// OnInitialized 方法
    /// </summary>
    protected override async Task OnInitializedAsync()
    {
        await this.GetTreeAsync();
        await base.OnInitializedAsync();
    }

    /// <summary>
    /// 弹出新增权限窗口
    /// </summary>
    private async Task ShowAuthorityModal()
    {
        _authorityModel = new();
        await _smailModal.Toggle();
    }

    /// <summary>
    /// 提交权限
    /// </summary>
    /// <param name="context"></param>
    private async Task SubmitAsync(EditContext context)
    {
        var createPermissionRequest = Mapping.Convert<CreatePermissionRequest>(_permissionModel);

        await _permissionService.CreateAsync(createPermissionRequest);

        await this.GetTreeAsync();

        _message.Success("提示", "创建成功");
    }

    /// <summary>
    /// 提交按钮权限
    /// </summary>
    /// <param name="context"></param>
    private Task SubmitAuthority(EditContext context)
    {
        var authorityModel = (AuthorityModel)context.Model;

        if (_permissionModel.Authority.Any(auth =>
                auth.KeyId != authorityModel.KeyId && auth.Code == authorityModel.Code))
        {
            _message.Error("错误提示", "Code重复");
        }
        else
        {
            var authority = _permissionModel.Authority.Find(auth => auth.KeyId == authorityModel.KeyId);
            if (authority == null)
            {
                _permissionModel.Authority.Add(authorityModel);
            }
            else
            {
                authority = authorityModel;
            }

            _smailModal.Close();
        }

        StateHasChanged();

        return Task.CompletedTask;
    }

    /// <summary>
    /// 编辑权限
    /// </summary>
    /// <returns></returns>
    private async Task ModifyAuthority(AuthorityModel model)
    {
        _authorityModel = model;

        await _smailModal.Toggle();
    }

    /// <summary>
    /// 移除权限
    /// </summary>
    private Task RemoveAuthority()
    {
        _permissionModel.Authority.Remove(_authorityModel);

        _smailModal.Close();

        return Task.CompletedTask;
    }

    /// <summary>
    /// 树节点点击事件
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    private async Task OnMenuItemClick(MenuItem item)
    {
        _selectMenuItem = item;

        await this.GetDetailsAsync();
    }

    #region Service 服务调用

    /// <summary>
    /// 获取树形菜单
    /// </summary>
    private async Task GetTreeAsync()
    {
        var tree = await _permissionService.GetTreeAsync();

        IconSideMenuItems = Mapping.Convert<List<MenuItem>>(tree);

        if (IconSideMenuItems.Any())
        {
            IconSideMenuItems.FirstOrDefault().IsActive = true;
        }

        StateHasChanged();
    }

    private async Task GetDetailsAsync()
    {
        PermissionDetailsResponse details = await _permissionService.GetDetailsAsync(new()
        {
            KeyIds = new()
            {
                Guid.Parse(_selectMenuItem.Target)
            }
        });

        _permissionModel = Mapping.Convert<PermissionModel>(details);

        StateHasChanged();
    }

    private async Task RemoveAsync()
    {
        await _permissionService.RemoveAsync(new()
        {
            KeyIds = new()
            {
                Guid.Parse(_selectMenuItem.Target)
            }
        });
        
        await this.GetTreeAsync();
    }

    #endregion
}